package Listdemo;

import java.util.Arrays;

public class MyArrayList {

    public int[] elem;
    public int UseSize;
    public static final int BIGGEST_CAPACITY = 2;

    public MyArrayList(){
        this.elem = new int[BIGGEST_CAPACITY];
    }


    public void DisPlay(){
        for (int i = 0; i < this.UseSize; i++) {
            System.out.print(this.elem[i]+" ");
        }
        System.out.println();
    }

    public boolean IsFull(){
        return UseSize == elem.length;
    }

    //新增元素，默认在数组最后添加
    public void Add(int data){
            if (IsFull()){
                elem = Arrays.copyOf(elem,2*elem.length);
        }
            elem[UseSize++] = data;
    }

    public void CheckAdd(int pos){
        if(pos<0 || pos>UseSize){
            throw new PosIndexNotLegalException("pos位置不合法");
        }
    }

    //新增元素在pos位置
    public void Add(int pos,int data){
        try{
            CheckAdd(pos);
            if(IsFull()){
//                System.out.println("扩容成功");
                elem = Arrays.copyOf(elem,2*elem.length);
            }
            for (int i = UseSize-1;i>=pos;i--){
                elem[i+1] = elem[i];
            }
            elem[pos] = data;
            UseSize++;
        }catch (PosIndexNotLegalException e){
            e.printStackTrace();
        }
    }

    //判断是否包含某个元素
    public boolean contains(int ToFind){
        for (int i = 0; i < UseSize; i++) {
            if(elem[i] == ToFind){
                return true;
            }
        }
        return false;
    }

    //查找某个元素对应下标
    public int IndexOf(int ToFind){
        for (int i = 0; i < UseSize; i++) {
            if(elem[i] == ToFind){
                return i;
            }
        }
        return -1;
    }

    public void CheckGetAdd(int pos){
        if(pos<0 || pos>=UseSize){
            throw new PosIndexNotLegalException("pos位置不合法");
        }
    }

    //获取pos位置的元素
    public int Get(int pos){
        int retVal = -1;
        try{
            CheckGetAdd(pos);
            retVal = elem[pos];
        }catch(PosIndexNotLegalException e){
            e.printStackTrace();
        }
        return retVal;
    }

    //给pos位置的元素更新为value
    public void Set(int pos,int value){
        CheckGetAdd(pos);
        elem[pos] = value;
    }

    public void ReMove(int key){
        int index = IndexOf(key);
        if(index == -1){
            System.out.println("没有你想要删除的数据！");
            return;
        }
        for (int i = index; i <UseSize-1 ; i++) {
            elem[i] = elem[i+1];
        }
        //elem[i] = null;防止内存泄露
        UseSize--;
    }

    public int Size(){
        return UseSize;
    }

    public void Clear(){
        /*
        for(int i = 0;i<UseSize;i++){
        elem[i] = null;
        }
         */
        UseSize = 0;
    }

}
